;
(function(w) {
  hlSelectUi()

  var app = new Vue({
    el: '#hireIndex',
    data: {
      listMenu: [
        {
          name: '草稿',
          code: 'CG'
        },
        {
          name: '审批中',
          code: 'WBP,WCP,SBP'
        },
        {
          name: '审批拒绝',
          code: 'FBP,FCP'
        },
        {
          name: '审批通过',
          code: 'SCP'
        },
        {
          name: '待结算',
          code: 'WJS'
        },
        {
          name: '已完成',
          code: 'FN'
        },
        {
          name: '已作废',
          code: 'ZF'
        }
      ],
      selectedListMenuCode: [],
      beginDate: '',
      endDate: '',
      proId: null,
      data: [],
      page: 1,
      pageCount: ['10'],
      currentPage: 1,
      totalCount: 0,
      totalPage: 0,
      pageCounts: [{name: '10', code: '10'}, {name: '15', code: '15'}, {name: '20', code: '20'}],
      beginDate:null,
      endDate:null,
      isShowSubmitConfirm: false,
      submitLayerData: {
        zlfName: '',
        total: '',
        withdrawDate: '',
        id: ''
      },
      policysList: [],
      rperson: {
        ids: [],
        name: null,
        list: []
      },
      tbTitleWidth: {
        width: 0 + 'px'
      },
      tbTotalWidth: {
        width: 957 + 'px'
      },
      tbOperateWidth:123,
      tbTitle: [],
      wzTableTitle: [],
      jdTableTitle: [],
      pzTableTitle: [],
      sortTableTitle: [],
      hasCustomConfig: 'N',
      configType: 'JD',
      isShowTableType: false,
      isShowTableLayer: false,
      curModule:'TZGL',
      tableType:'scroll',   //  scroll滑动表  fixed固定表
      isScroll:false,
      keyword: ''
    },
    filters: {
      formatDate: function(time) {
        if (time === undefined) {
          return '--'
        }
        var date = new Date(time)
        return hlDateUtil.formatUTCDate(date, 'yyyy-MM-dd')
      },
      formatNum: function(item) {
        if (item === undefined) return '--'
        return hlNumberUtil.formatNum(item)
      },
      auditState: function(state) {
        return hlCodeConvert.withdrawAuditState(state)
      },
      numCompare: function(value) {
        if (value > 0) {
          return Math.abs(value).toFixed(2) + '(应收)'
        }
        if (value < 0) {
          return Math.abs(value).toFixed(2) + '(应退)'
        }
      },
      formatUndefined: function(item) {
        if (!item && item != 0) return '--'
        return item
      }
    },
    methods: {
      selectMenuList(){
        this.currentPage = 1
        this.search()
      },
      resetTabbar(){
        this.selectedListMenuCode = []
        this.currentPage = 1
        this.search()
      },
      //获取租户的数据访问策略
      policys: function() {
        var _this = this;
        hlhttp.get({
          url: 'data_policys',
          success: function(res) {
            _this.policysList = res;
          }
        })
      },
      //输入对接人进行搜索
      onInputDJR: function(e) {
        if (!this.rperson.name) {
          if (!e.data) return;
          this.rperson.name = e.data;
        }
        this.getDataGroup()
      },
      //判断有没有ids
      ifrpersonIds: function() {
        if (!this.rperson.ids.length) {
          this.rperson.name = null
        }
      },
      //设置对接人name，获取id
      setRperson: function(name, id) {
        this.rperson.ids = [];
        this.rperson.name = name;
        this.rperson.ids.push(id)
        this.rperson.list = [];
      },
      //搜索负责人工作组组员列表
      getDataGroup: function() {
        var _this = this;
        _this.rperson.ids = [];
        hlhttp.get({
          url: 'data_group/users/_search',
          data: {
            keyword: _this.rperson.name || '#'
          },
          success: function(res) {
            _this.rperson.list = res;
            for (var i = 0; i < _this.rperson.list.length; i++) {
              if (_this.rperson.name) {
                if (_this.rperson.name.match(res[i])) {
                  _this.rperson.ids.push(res[i].userId)
                }
              }
            }
          }
        })
      },
      // 初始化项目 默认加载所有的项目数据
      initProgrammer: function() {
        var self = this;
        getProduct(
          function(arr) {
            self.proId = arr[1].join(',') || '#'
            self.search()
          },
          function(arr) {
            self.proId = arr[0].join(',') || arr[1].join(',') || '#'
            self.search()
          },
          function(arr) {
            self.proId = arr[0].join(',') || arr[1].join(',') || '#'
            self.search()
          }
        )
      },
      //获取列表
      search: function() {
        var pid = [],pidb = [];
        const self = this;

        hlhttp.get({
          url: 'withdraws',
          data: {
            audit_state: self.selectedListMenuCode.length ? self.selectedListMenuCode.join() : '#',
            begin_date: self.beginDate || '#',
            end_date: self.endDate || '#',
            project_ids: self.proId,
            page: self.currentPage, //请求页
            page_count: self.pageCount[0], //每页数量,
            rperson_id: self.rperson.ids.toString() || '#',
            keyword: self.keyword
          },
          success: function(res) {
            loginPrem.loginList()

            self.data = res.withdraws
            self.totalCount = res.totalCount
            self.totalPage = res.totalPage

            self.getHeadConfig()
          }
        })
      },
      //重置
      resetBtn: function() {
        var _this = this;
        this.beginDate = null;
        this.endDate = null;
        this.keyword = '';
				this.currentPage = 1
        this.rperson = {
          ids: [],
          name: null,
          list: []
        }
        setTimeout(function() {
          _this.search()
        }, 200);
      },
      //查询数据
      pagesearch: function() {
        var self = this;
        var pages = {
          "turnPage": function(n) {
            self.currentPage = n
            setTimeout(function() {
              self.search();
            }, 200);
          }
        }
        $("#page").initPage(1, 1, pages.turnPage);
      },
      // 每页数量选择
      pageSelect: function(arr) {
        const self = this;
        this.pageCount = [arr[0].code]
        this.currentPage = 1
        setTimeout(function() {
          self.search();
        }, 200);
      },
      //合同终止校验
      checkWithout(zlfName, withdrawDate, amountReceived, amountRefund, id, pid,contractId){
        var that = this
        hlhttp.get({
          url: 'withdraw/_check',
          data: {
            'contract_id': contractId
          },
          success: function(res) {
            that.submitBusinessAudit(zlfName, withdrawDate, amountReceived, amountRefund, id, pid)
          },
        })
      },

      // 提交草稿、业务、财务审核不通过状态到待业务审核状态
      submitBusinessAudit: function(zlfName, withdrawDate, amountReceived, amountRefund, id, pid) {
        var is = this;

        hlhttp.put({
          url: 'bpm/check_project_use',
          data: {
            bpm_key: 'WT',
            project_id: pid
          },
          success: function(res) {
            if (res.flag == 'N') {
              hl.toast('请先配置流程')
              return
            }
            ebDx()
          }
        })

        function ebDx() {
          var withdrawTime, total;
          if (withdrawDate == undefined) withdrawTime = '--';
          if (withdrawDate !== undefined) withdrawTime = hlDateUtil.formatUTCDate(withdrawDate, 'yyyy-MM-dd');
          if ((amountReceived - amountRefund) < 0) {
            total = hlNumberUtil.formatNum(Math.abs(amountReceived - amountRefund).toFixed(2)) + '元(应退)'
          }
          if ((amountReceived - amountRefund) == 0) {
            total = '0.00'
          }
          if ((amountReceived - amountRefund) > 0) {
            total = hlNumberUtil.formatNum(Math.abs(amountReceived - amountRefund).toFixed(2)) + '元(应收)'
          }

          var obj = {
            zlfName: zlfName,
            total: total,
            withdrawDate: withdrawTime,
            id: id
          }

          is.isShowSubmitConfirm = true;
          is.$set(is.$data, 'submitLayerData', obj)
        }
      },
      // 关闭提交确认框
      closeSubmitConfirmLayer: function() {
        this.isShowSubmitConfirm = false;
      },
      // 确认提交退租
      confirmSubmitWithdraw: function() {
        var self = this;
        hlhttp.put({
          url: 'withdraw/wbp',
          data: {
            id: self.submitLayerData.id
          },
          success: function(data) {
            hl.toast('提交成功')
            self.isShowSubmitConfirm = false;
            self.search()
          }
        })
      },

      // 对应表头字段表宽度值
      getThWidth(val) {
        var res = 70;
        switch (val) {
          case '序':
            res = '40'
            break;
          case '退租时间':
            res = '100'
            break;
          case '退租单号':
            res = '120'
            break;
          case '客户':
            res = '140'
            break;
          case '应收金额(元)':
            res = '120'
            break;
          case '应退金额(元)':
            res = '120'
            break;
          case '合计(元)':
            res = '120'
            break;
          case '退租状态':
            res = '120'
            break;
        }
        return res;
      },
      // 对应表头字段是否排序
      getThSort(val) {
        var res;
        switch (val) {
          case '序':
            res = 'N'
            break;
          case '退租时间':
            res = 'N'
            break;
          case '退租单号':
            res = 'N'
            break;
          case '客户':
            res = 'N'
            break;
          case '应收金额(元)':
            res = 'N'
            break;
          case '应退金额(元)':
            res = 'N'
            break;
          case '合计':
            res = 'N'
            break;
          case '退租状态':
            res = 'N'
            break;
          default:
        }
        return res;
      },
      // 获取自定义表头配置
      getHeadConfig() {
        var self = this;
        hlhttp.get({
          url: 'contract/column_header_config',
          data: { 'module': self.curModule },
          success: function(data) {
            var wzTableTitle = [];
            data.systemConfig.forEach((el, i) => {
              var obj = {};
              el['width'] = self.getThWidth(el.name)
              el['isSort'] = self.getThSort(el.name)
              obj = JSON.parse(JSON.stringify(el))
              obj['isShow'] = 'Y'
              wzTableTitle.push(obj)
            })

            data.customConfig.forEach(el => {
              var obj = {};
              el['width'] = self.getThWidth(el.name)
              el['isSort'] = self.getThSort(el.name)
              el['isActive'] = 'N'
            })

            self.wzTableTitle = wzTableTitle;
            self.jdTableTitle = data.systemConfig;
            self.pzTableTitle = data.customConfig;
            self.sortTableTitle = JSON.parse(JSON.stringify(data.customConfig))
            self.hasCustomConfig = data.hasCustomConfig;
            self.configType = data.configType;
            self.refreshTableData()
          }
        })
      },
      // 计算表格标题栏宽度
      calTbTitleWidth() {
        var self = this,
          width = 4;
        self.tbTitle.forEach(el => {
          if (el.isShow == 'Y') width += Number(el.width);
        })
        return width
      },
      // 计算表格外容器宽度
      calTbWidth() {
        var width = this.calTbTitleWidth() + 124;
        return width > 957 ? 957 : width
      },
      // 刷新当前表格
      refreshTableData() {
        var self = this;

        if (self.configType == 'JD') self.tbTitle = self.jdTableTitle;
        if (self.configType == 'WZ') self.tbTitle = self.wzTableTitle;
        if (self.configType == 'PZ') self.tbTitle = self.pzTableTitle;
        const tbTitleWidth = self.calTbTitleWidth();
        self.tbTitleWidth = { width:tbTitleWidth < 839 ? '100%' : tbTitleWidth + 'px' };
        self.tbTotalWidth = { width: self.calTbWidth() + 'px'};
        // 根据表格title总宽度 来判断当前显示哪种表格类型
        if(tbTitleWidth > 833) self.tableType = 'scroll';
        if(tbTitleWidth <= 833) self.tableType = 'fixed';
      },
      showScroll(){
        this.isScroll = true;
      },
      hideScroll(){
        this.isScroll = false;
      },
      // 保存当前所选表格类型
      saveTableType(type) {
        var self = this;
        hlhttp.post({
          url: 'contract/column_header_select',
          data: {
            'module': self.curModule,
            'config_type': type
          },
          success: function(data) {
            self.refreshTableData()
          }
        })
      },
      // 保存当前表头
      saveTableTitle(data, isLayer) {
        var self = this;

        function dataWrap(data) {
          var res = [];
          data.forEach((el, i) => {
            res.push({
              'id': el.id,
              'name': el.name,
              'display_name': el.displayName ? el.displayName : '#',
              'value': el.value,
              'is_show': el.isShow,
              'seq': el.seq ? el.seq : '#'
            })
          })
          return res;
        }

        hlhttp.post({
          url: 'contract/column_header_config',
          data: {
            'module': self.curModule,
            'has_custom_config': self.hasCustomConfig,
            'custom_config': JSON.stringify(dataWrap(data))
          },
          success: function(res) {
            if (isLayer) {
              hl.toast('保存成功')
              self.pzTableTitle = JSON.parse(JSON.stringify(data));
              self.isShowTableLayer = false;
              self.refreshTableData()
            }
          }
        })

      },
      selectTableType(type) {
        var self = this;
        if (type == 'JD') {
          self.configType = 'JD'
          self.saveTableType(type);
          return;
        }
        if (type == 'WZ') {
          self.configType = 'WZ'
          self.saveTableType(type);
          return;
        }
        if (type == 'PZ') {
          self.configType = 'PZ'
          self.saveTableType(type);
          // 如果当前自定义表没有配置过 则强制保存完整表头数据
          if (self.hasCustomConfig == 'N') self.saveTableTitle(self.wzTableTitle)
          return;
        }
      },
      showTableTypeComponents() {
        this.isShowTableType = true;
      },
      hideTableTypeComponents() {
        this.isShowTableType = false;
      },
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      showhighLightTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isActive', 'Y')
      },
      removehighLightTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isActive', 'N')
      },
      selectedTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isShow', 'Y')
      },
      cancelSelectedTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isShow', 'N')
      },
      // 确定提交自定义表格
      confirmSubmitTable() {
        var self = this;
        self.saveTableTitle(self.sortTableTitle, true)
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      }
    },
    mounted: function() {
      this.policys()
      this.initSortable()
      this.initProgrammer()
      var _this = this;
      document.body.onclick = function() {
        _this.rperson.list = [];
      }
    }
  })

}(window))
